import {
  ElButton,
  ElDialog,
  ElSpace,
  ElUpload,
  type UploadRequestOptions
} from 'element-plus'
import { defineComponent, reactive, toRefs } from 'vue'

import { userApi } from '@/apis'
import { downloadFile, getElementFnFromInstance } from '@/utils'

import styles from './ImportDialog.module.css'

export default defineComponent({
  name: 'ImportDialog',
  emits: ['success'],
  setup(_, { emit }) {
    const state = reactive({
      show: false,
      importLoading: false,
      requested: false
    })

    const { $notify } = getElementFnFromInstance()

    /**
     * 打开
     * @description 供父组件调用
     */
    function open() {
      state.show = true
    }

    /**
     * 关闭
     */
    function handleClose() {
      state.show = false

      if (state.requested) {
        state.requested = false
        emit('success')
      }
    }

    /**
     * 下载模板
     */
    async function handleDownloadTemplate() {
      const res = await userApi.exportUserTemplate()

      downloadFile(res)
    }

    /**
     * 导入模板
     */
    async function handleUploadTemplate(options: UploadRequestOptions) {
      return new Promise((resolve, reject) => {
        state.importLoading = true

        const file = options.file
        const formData = new FormData()
        formData.append('file', file)
        userApi
          .importUserTemplate(formData)
          .then(value => {
            const { success, fail } = value

            $notify.info({
              message: `导入用户：成功${success}，失败${fail}`
            })
            resolve(null)
          })
          .catch(reject)
          .finally(() => {
            state.importLoading = false
          })
      })
    }

    return {
      ...toRefs(state),
      open,
      handleClose,
      handleDownloadTemplate,
      handleUploadTemplate
    }
  },
  render() {
    return (
      <ElDialog
        v-model={this.show}
        title="用户导入"
        width="600px"
        beforeClose={this.handleClose}
        destroyOnClose
      >
        {{
          default: () => (
            <div class={styles.uploadContent}>
              <ElUpload
                accept=".xls,.xlsx"
                limit={1}
                showFileList={false}
                httpRequest={this.handleUploadTemplate}
              >
                <ElButton type="primary" loading={this.importLoading}>
                  上传
                </ElButton>
              </ElUpload>
              <div style={{ marginTop: '10px' }}>
                <span>仅允许导入xls、xlsx格式文件。</span>
                <ElButton
                  type="primary"
                  size="small"
                  link
                  onClick={this.handleDownloadTemplate}
                >
                  下载模板
                </ElButton>
              </div>
            </div>
          ),
          footer: () => (
            <ElSpace>
              <ElButton onClick={this.handleClose}>取消</ElButton>
            </ElSpace>
          )
        }}
      </ElDialog>
    )
  }
})
